package com.wyth.lottery.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.wyth.lottery.R;
import com.wyth.lottery.base.BaseActivity;
import com.wyth.lottery.base.SaveUtils;
import com.wyth.lottery.bean.SSQBean;
import com.wyth.lottery.bean.SSQDataBean;
import com.wyth.lottery.bean.SSQSelectBean;
import com.wyth.lottery.service.Entity.Detail;
import com.wyth.lottery.service.presenter.DetailPresenter;
import com.wyth.lottery.service.view.DetailView;
import com.wyth.lottery.utils.BuildParamUtils;
import com.wyth.lottery.utils.MainThread;
import com.wyth.lottery.utils.MyApplication;
import com.wyth.lottery.utils.Vbar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.OnClick;

/**
 * Created by phh on 2017/11/4.
 * <p>
 * 扫码支付的界面
 */

public class ZFPayActivity extends BaseActivity {
    private Vbar b = new Vbar();
    protected boolean decodestate;
    private boolean state;


    private DetailPresenter mDetailPresenter;
    private String detailInfo;


    Handler mHandler = new Handler();
    Runnable mRunnable2=new Runnable() {
        @Override
        public void run() {
            initData();
        }
    };
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mDetailPresenter.getDetail(detailInfo);
        }
    };
    public String mStr;

    private void startVbar() {

        decodestate = false;

        SystemClock.sleep(10);//暂10毫秒后程序继续执行


        //打开扫码器
        state = b.vbarOpen();
        System.out.println("打开扫码器");

        //确认是否打开扫码器
        if (state) {
            decodestate = true;
        } else {
            decodestate = false;
        }
        mThread.start();
    }

    Thread mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (decodestate) {
                //开始扫码
                mStr = b.vbarScan();
                System.out.println("开始扫码-----------------------------------");
                System.out.println(mStr + "--------------------------------++++++++++++++++");
                if (mStr != null) {
                    decodestate = false;
                    System.out.println("接收到扫码,开始提交数据********************************************88");
                    b.vbarClose();
                    b.vbarBeep(1);
                    mHandler.post(mRunnable2);
                    mHandler.post(mRunnable);
                }
                SystemClock.sleep(500);
                MainThread instance = MainThread.getInstance();

                instance.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mStr != null) {
                            startAct(mStr);
                        }
                    }
                });
            }
        }
    });

    private void startAct(String s) {

    }

    @Override
    protected int getContentID() {
        return R.layout.activity_zfpay;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initDate() {
        startVbar();

    }


    private void initData() {
        mDetailPresenter = new DetailPresenter(this);
        Gson gson = new Gson();
        Map<String, String> param = new HashMap<String, String>();
        param.put("sid", "yhl");
        param.put("cmd", "3300");
        param.put("platform", "andorid");
        param.put("sysVer", "android4.2");
        param.put("softVer", "v1.0");
        param.put("width", "800");
        param.put("height", "1024");
        param.put("machId", "aaaaa");
        param.put("func", "wap");

        //拼接购物车的数据双色球数据
        SSQBean ssqBean = getSSQBean();
        String s = gson.toJson(ssqBean);
        param.put("msg", s);
        System.out.println(s+"-----------------------------");
        String currMd5 = BuildParamUtils.buildMd5(param, "yhlkey");
        param.put("md5", currMd5);
        detailInfo = gson.toJson(param);
        mDetailPresenter.onCreate();
        mDetailPresenter.attachView(mBookView);

    }

    @NonNull
    private SSQBean getSSQBean() {
        int tvMoney = SaveUtils.getGoodsInfos().mTvMoney;
        SSQBean ssqBean = new SSQBean();
        ssqBean.setAuthCode(mStr);
        ssqBean.setUserCode("20171103175112718012");
        ssqBean.setLotteryId("001");
        ssqBean.setPlayId("01");
        ssqBean.setBuyType(String.valueOf(1));
        ssqBean.setDescription("");
        ssqBean.setPrivacy("0");
        ssqBean.setBuyAmount(2);
        ssqBean.setFloorsAmount(0);
        ssqBean.setWereMin(1);
        ssqBean.setWinStop(0);
        ssqBean.setStopAmount(0);
        ssqBean.setTotalAmount(tvMoney*SaveUtils.getGoodsInfos().mTvMoneyNumberBei);
        List<SSQBean.BuyNumberArrayBean> mlist = getBuyNumberArrayBeen();
        ssqBean.setBuyNumberArray(mlist);
        List<SSQBean.IssueArrayBean> missue = new ArrayList<>();
        SSQBean.IssueArrayBean issueArrayBean = new SSQBean.IssueArrayBean();
        issueArrayBean.setIssue(SaveUtils.getGoodsInfos().mName+"");
        issueArrayBean.setMultiple(SaveUtils.getGoodsInfos().mTvMoneyNumberBei);
        missue.add(issueArrayBean);
        ssqBean.setIssueArray(missue);
        return ssqBean;
    }

    @NonNull
    private List<SSQBean.BuyNumberArrayBean> getBuyNumberArrayBeen() {
        List<SSQBean.BuyNumberArrayBean> mlist = new ArrayList<>();
        for (SSQDataBean ssqDataBean : SaveUtils.getGoodsInfos().mlist) {
            String type = ssqDataBean.getType();
            if (type.equals("标准投注")) {
                SSQBean.BuyNumberArrayBean buyNumberArrayBean = new SSQBean.BuyNumberArrayBean();
                buyNumberArrayBean.setItem(ssqDataBean.getInt()+""); //注数
                System.out.println(SaveUtils.getGoodsInfos().mTvMoneyNumberBei+"----------------------------------倍数");
                buyNumberArrayBean.setAmount(ssqDataBean.getMoney());  //金额
                buyNumberArrayBean.setPlayId("01");     //玩法编码
                List<SSQSelectBean> red = ssqDataBean.getRed();
                List<SSQSelectBean> mblue = ssqDataBean.getMblue();
                if (red.size() > 6 || mblue.size() > 1) {
                    buyNumberArrayBean.setPollId("02");   //复试
                } else {
                    buyNumberArrayBean.setPollId("01");  //单式
                }
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < red.size(); i++) {
                    if (i == red.size() - 1) {
                        stringBuffer.append(red.get(i).getText());
                    } else {
                        stringBuffer.append(red.get(i).getText() + ",");
                    }
                }
                stringBuffer.append("#");
                for (int i = 0; i < mblue.size(); i++) {
                    if (i == mblue.size() - 1) {
                        stringBuffer.append(mblue.get(i).getText());
                    } else {
                        stringBuffer.append(mblue.get(i).getText() + ",");
                    }
                }
                buyNumberArrayBean.setBuyNumber(stringBuffer.toString());
                mlist.add(buyNumberArrayBean);
            } else if (type.equals("胆拖投注")) {
                StringBuffer stringBuffer = new StringBuffer();
                SSQBean.BuyNumberArrayBean buyNumberArrayBean = new SSQBean.BuyNumberArrayBean();
                /**
                 * buyNumber : 01,02,03,04,09@06,07#04,07
                 * playId : 01
                 * pollId : 03
                 * item : 4
                 * amount : 8
                 */
                buyNumberArrayBean.setPlayId("01");
                buyNumberArrayBean.setPollId("03");
                buyNumberArrayBean.setItem(ssqDataBean.getInt()+"");
                buyNumberArrayBean.setAmount(ssqDataBean.getMoney());
                List<SSQSelectBean> red = ssqDataBean.getRed();
                List<SSQSelectBean> mblue = ssqDataBean.getMblue();
                List<String>mBZ=new ArrayList<>();
                List<String>mDT=new ArrayList<>();

                getTypeData(red, mBZ, mDT);
                for (int i = 0; i < mBZ.size(); i++) {
                    if (i==mBZ.size()-1){
                        stringBuffer.append(mBZ.get(i));
                    }else {
                        stringBuffer.append(mBZ.get(i)+",");
                    }
                }
                stringBuffer.append("@");
                for (int i = 0; i < mDT.size(); i++) {
                    if (i==mDT.size()-1){
                        stringBuffer.append(mDT.get(i));
                    }else {
                        stringBuffer.append(mDT.get(i)+",");
                    }
                }
                stringBuffer.append("#");
                for (int i = 0; i < mblue.size(); i++) {
                    if (i==mblue.size()-1){
                        stringBuffer.append(mblue.get(i).getText());
                    }else {
                        stringBuffer.append(mblue.get(i).getText()+",");
                    }
                }

                buyNumberArrayBean.setBuyNumber(stringBuffer.toString());
                mlist.add(buyNumberArrayBean);
            }
        }
        return mlist;
    }

    private void getTypeData(List<SSQSelectBean> red, List<String> mBZ, List<String> mDT) {
        for (int i = 0; i < red.size(); i++) {
            SSQSelectBean ssqSelectBean = red.get(i);
            boolean isBoolean = ssqSelectBean.isBoolean;
            boolean selectBoolean = ssqSelectBean.selectBoolean;
            if (selectBoolean == true && isBoolean == true) {
                mBZ.add(ssqSelectBean.getText());
            } else if (selectBoolean == true && isBoolean == false) {
                mDT.add(ssqSelectBean.getText());
            }
        }
    }

    private DetailView mBookView = new DetailView() {

        @Override
        public void onSuccess(Detail detail) {
            String code = detail.getCode();
            if (code.equals("0000")){
                String msg = detail.getMsg();
                String result = detail.getResult();
                System.out.println(code + "-------------aaaaaaaaaaaaaaaa" + msg + "----------------aaaaaaaaaaaa" + result);
                Intent intent = new Intent(MyApplication.getContext(), PayOKActivity.class);
                intent.putExtra("PayOKActivity", result);

                startActivity(intent);
                SaveUtils.getGoodsInfos().ClearSSQData();
            }else {
                String code1 = detail.getCode();
                String msg = detail.getMsg();
                String result = detail.getResult();
                System.out.println(code1+"-----------------"+msg+"------------------"+result);
                onError(detail.getMsg());
            }

        }

        @Override
        public void onError(String result) {
            System.out.println(result + "--------------------------------------------");
        }
    };

    @OnClick(R.id.tv_return)
    public void onViewClicked() {
        startActivity(new Intent(MyApplication.getContext(), MainActivity.class));
        finish();

        decodestate = false;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mRunnable);
    }
}
